/*
 * Poyke Framework
 * Copyright (C) 2010 Poyke <http://code.google.com/p/poyke/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "StdAfx.h"

CoreLoader *CoreLoader::_instance = NULL;

CoreLoader *CoreLoader::GetInstance()
{
	if(_instance == NULL)
	{
		_instance = new CoreLoader();
	}
	return _instance;
}

CoreLoader::CoreLoader()
{
	// pass
}

LOAD_CORE_RESULTS CoreLoader::LoadCore(bool just_crashed)
/*
 *	Attempt to load the Core.dll file, and call the CORE_PROTO_INIT function from it.
 *  If fails to find said function, attempts to unload the DLL completely.
 */
{
	_hCore = POYKE_LOAD_MODULE("core");
	if(!_hCore)
	{
		return LOAD_CORE_FAIL_NO_DLL;
	}
	_InitCore = (CORE_PROTO_INIT)POYKE_GET_SYMBOL(_hCore,"CoreInit");
	if(!_InitCore)
	{
		if(!POYKE_DEL_MODULE(_hCore))
		{
			Logging::Warning("CoreLoader", "No Core entry function found and core could not be unloaded");
		}
		return LOAD_CORE_FAIL_NO_ENTRY;
	}
	_SaveState = (CORE_PROTO_SAVE)POYKE_GET_SYMBOL(_hCore, "SaveState");
	if(!_SaveState)
	{
		if(!POYKE_DEL_MODULE(_hCore))
		{
			Logging::Warning("CoreLoader", "No Save State function found and core could not be unloaded");
		}
		return LOAD_CORE_FAIL_NO_SAVESTATE;		
	}
	Logging::Debug("CoreLoader", "Calling CoreInit");
	_InitCore(just_crashed);
	return LOAD_CORE_SUCCESS;
}

UNLOAD_CORE_RESULTS CoreLoader::UnloadCore(bool force)
/*
 *	Tell the ThreadMgr to halt all threads, signal the core to save state,
 *  and unload the DLL.
 */
{
	if(force || sThreadMgr->HaltThreads())
	{
		SignalSaveState();
		if(POYKE_DEL_MODULE(_hCore))
			return UNLOAD_CORE_SUCCESS;
		else
			return UNLOAD_CORE_FAIL_UNKNOWN;
	}
	else
	{
		return UNLOAD_CORE_FAIL_IN_USE;
	}
}

void CoreLoader::SignalSaveState()
/*
 *	Signal the core to Save State.
 *  If the core fails to Save State we're still proceeding with whatever
 *  because we rely on incremental state saves anyways
 */
{
	if(!_SaveState())
	{
		Logging::Warning("CoreLoader", "Unable to save state. Continuing anyways");
	}
}
